﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Smart.Admin.Domain.Repository;
using Smart.Admin.Domain.Service;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Text;
using Smart.Admin.Domain.Model.Entity;
using Newtonsoft.Json;
using InitQ.Cache;
using Smart.Admin.Domain.Model.Const;

namespace Smart.Admin.Api.Filters
{
    public class ActionFilterAttribute : Attribute, IAsyncActionFilter
    {

        private readonly ILogger<ActionFilterAttribute> logger;
        private readonly ICacheService _redisService;

        public ActionFilterAttribute(ILoggerFactory loggerFactory,
                                    ICacheService redisService)
        {
            logger = loggerFactory.CreateLogger<ActionFilterAttribute>();
            _redisService = redisService;
        }

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {

            //if (!context.ModelState.IsValid)
            //{
            //    var result = context.ModelState.Keys
            //           .SelectMany(key => context.ModelState[key].Errors.Select(x => new { key = key, message = x.ErrorMessage }))
            //           .FirstOrDefault();
            //    if (result != null)
            //    {
            //        context.Result = new JsonResult(new { code = "-1", message = $"{result.key}参数校验失败,{result.message}" });
            //        return;
            //    }
            //}
            //#region 根据注解允许匿名访问
            //var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
            ////controller
            //var controllerAttributes = actionDescriptor.MethodInfo.DeclaringType.GetCustomAttributes(typeof(AllowAnonymousAttribute), true);
            //if (controllerAttributes != null && controllerAttributes.Length > 0)
            //{
            //    await next();
            //    return;
            //}
            ////action
            //var actionAttributes = actionDescriptor.MethodInfo.GetCustomAttributes(typeof(AllowAnonymousAttribute), true);
            //if (actionAttributes != null && actionAttributes.Length > 0)
            //{
            //    await next();
            //    return;
            //}
            //#endregion

            //var request = context.HttpContext.Request;
            ////请求的唯一ID
            //var requestId = context.ActionDescriptor.Id;
            //var startTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.ffff", DateTimeFormatInfo.InvariantInfo));
            //var parms = "";
            //// post 请求方式获取请求参数方式
            //try
            //{
            //    if (request.Method.ToLower().Equals("post"))
            //    {
            //        Stream stream = request.Body;
            //        byte[] buffer = new byte[request.ContentLength.Value];
            //        stream.Position = 0L;
            //        await stream.ReadAsync(buffer, 0, buffer.Length);
            //        parms = Encoding.UTF8.GetString(buffer);
            //        parms = Regex.Replace(parms, @"[\r\n]", "");
            //    }
            //}
            //catch (Exception e)
            //{


            //}
            ////菜单对象
            //var res = await _menuService.GetMenuByUrl(request.Path.ToString().ToLower());
            //if (res.code == "-1" || res.data == null)
            //{
            //    res.data = new MenuEntity() { Name = "未知菜单", Id = -1 };
            //}
            ////TODO 权限判断

            //var ip = "";
            //if (context.HttpContext.Request.Headers.ContainsKey("X-Forwarded-For"))
            //{
            //    ip = context.HttpContext.Request.Headers["X-Forwarded-For"].ToString();
            //}
            //else
            //{
            //    ip = context.HttpContext.Connection.RemoteIpAddress.ToString();
            //}

            //var controllerName = context.RouteData.Values["controller"] as string;
            //var actionName = context.RouteData.Values["action"] as string;

            ////日志
            //ManagerLogEntity log = new ManagerLogEntity()
            //{
            //    FromBady = parms,
            //    CreateTime = DateTime.Now,
            //    LoginIp = ip,
            //    UrlParam = request.QueryString.ToString(),
            //    RequestId = requestId,
            //    NId = res.data.Id,
            //    Roles = context.HttpContext.User.Claims.ToList().FirstOrDefault(m => m.Type.Contains("Roles"))?.Value,
            //    MenuName = res.data.Name,
            //    Api = request.Path
            //};
            ////脱敏处理
            //var hideActionList = new List<string>() 
            //{
            //    "resetmanngerpwd",
            //    "createmanagerinfo",
            //    "updatemanagerinfo",
            //};

            //if (hideActionList.Contains(actionName.ToLower()))
            //{
            //    log.FromBady = "******";
            //    log.UrlParam = "******";
            //}

            //var mId = context.HttpContext.User.Claims.ToList().FirstOrDefault(m => m.Type.Contains("Id"))?.Value;
            //if (!string.IsNullOrEmpty(mId))
            //{
            //    log.MId = Convert.ToInt64(mId);
            //    log.ManagerName = context.HttpContext.User.Claims.ToList().FirstOrDefault(m => m.Type.Contains("Name"))?.Value;
            //}
            await next();
            //await EndMangerLog(context, log, startTime);
        }

        //private async Task EndMangerLog(ActionExecutingContext context, ManagerLogEntity log, DateTime startTime)
        //{
        //    var endTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.ffff", DateTimeFormatInfo.InvariantInfo));
        //    log.ExecuteTime = Convert.ToDecimal((endTime - startTime).TotalSeconds);
        //    await _redisService.ListLeftPushAsync(RedisMapp.mes_sys_queue_manager_log, JsonConvert.SerializeObject(log));
        //}



    }
}
